package com.xxg.renrenuser.service;

import com.alibaba.fastjson.JSON;
import com.xxg.renrencommon.domain.result.BaseResult;
import com.xxg.renrenuser.dao.ExpressAddressInfoDao;
import com.xxg.renrenuser.dao.bean.ExpressAddressInfo;
import com.xxg.renrenuser.domain.query.AddAddressQuery;
import com.xxg.renrenuser.domain.query.DeleteAddressQuery;
import com.xxg.renrenuser.domain.query.EditAddressQuery;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 地址管理接口实现
 *
 * @author xxg
 * @date 2020/10/21
 */
@Service
@AllArgsConstructor
public class AddressServiceImpl implements AddressService {
    private final ExpressAddressInfoDao expressAddressInfoDao;

    @Override
    public BaseResult<Void> addAddress(AddAddressQuery addAddressQuery) {
        String jsonString = JSON.toJSONString(addAddressQuery);
        ExpressAddressInfo addressInfo = JSON.parseObject(jsonString, ExpressAddressInfo.class);
        String addressId = UUID.randomUUID().toString().replace("-", "");
        addressInfo.setAddressId(addressId);
        // 当前为默认地址，则将历史默认更新非默认状态
        if (addressInfo.getDefaultAddress() == 1) {
            expressAddressInfoDao.updateAddressByUserId(addressInfo.getUserId());
        }
        expressAddressInfoDao.insertSelective(addressInfo);
        return new BaseResult<>();
    }

    @Override
    public BaseResult<Void> editAddress(String userId, EditAddressQuery editAddressQuery) {
        String jsonString = JSON.toJSONString(editAddressQuery);
        ExpressAddressInfo addressInfo = JSON.parseObject(jsonString, ExpressAddressInfo.class);
        addressInfo.setUpdateTime(new Date());
        addressInfo.setUserId(userId);
        // 当前为默认地址，则将历史默认更新非默认状态
        if (addressInfo.getDefaultAddress() == 1) {
            expressAddressInfoDao.updateAddressByUserId(addressInfo.getUserId());
        }
        expressAddressInfoDao.updateByAddressIdSelective(addressInfo);
        return new BaseResult<>();
    }

    @Override
    public BaseResult<List<ExpressAddressInfo>> getAddressList(String userId) {
        List<ExpressAddressInfo> addressInfos = expressAddressInfoDao.getAddressListByUserId(userId);
        return new BaseResult<>(addressInfos);
    }

    @Override
    public BaseResult<Void> deleteAddress(DeleteAddressQuery deleteAddressQuery) {
        expressAddressInfoDao.deleteByAddressId(deleteAddressQuery.getAddressId());
        return new BaseResult<>();
    }
}
